package cn.xyt.service;

import static java.nio.ByteOrder.LITTLE_ENDIAN;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.tom.db.jdbc.simple.DBUtil;
import cn.tom.kit.IoBuffer;
import cn.xyt.dto.Form;
import cn.xyt.dto.Header;
import cn.xyt.dto.Message;

public class BaseService {
	
	protected static String SUCCESS = "命令执行成功";
	protected static String FAILD = "命令执行失败";
	
	public final Logger logger = LoggerFactory.getLogger(BaseService.class);

	public static int byteToInt(byte b) {  
	    //Java 总是把 byte 当做有符处理；我们可以通过将其和 0xFF 进行二进制与得到它的无符值  
	    return b & 0xFF;  
	}  
	
	public static byte toByte(String b) {  
	    //Java 总是把 byte 当做有符处理；我们可以通过将其和 0xFF 进行二进制与得到它的无符值  
	    return (byte)(Integer.parseInt(b)&0xFF);  
	}  

	public IoBuffer getLittleBuf(){  //获得小端序 bytebuf
		IoBuffer buf = IoBuffer.allocate(200);
		buf.buf().order(LITTLE_ENDIAN);
		return buf;
	}
	
	public IoBuffer getLittleBuf(int length){
		IoBuffer buf = IoBuffer.allocate(length);
		buf.buf().order(LITTLE_ENDIAN);
		return buf;
	}
	
	public String getsoftversion(byte[] b){
		String softVersion = new StringBuffer()
		.append((int)b[0]&0xff).append('.').append((int)b[1]&0xff).append('.')
		.append((int)b[2]&0xff).append('.').append(String.format("%03d", (int)b[3]&0xff)).toString();
		return softVersion;
	}
	
	public int getUid(int deviceid){
		int uid = DBUtil.getInt("select uid from deviceauth a join deviceset b on a.id = b.deviceid where a.id = ?", deviceid);
		return uid;
	}
	
	private static AtomicInteger _nextInc = new AtomicInteger( (new java.util.Random()).nextInt() );
	
	public Message getdefaultMessage(Form form){
		int cmd = Integer.parseInt(form.getCmd(), 16);
		String deviceid = form.getDeviceid();
		Header header = new Header();
		header.setSerial((short)(System.currentTimeMillis()+_nextInc.getAndIncrement()));
		header.setDeviceid(Integer.parseInt(deviceid));
		header.setMsgid((byte)cmd);
		Message message = new Message(header, new byte[]{});
		return message;
	}
	
	
	public Map<String, Object> error(String msg, Object... obj){
		HashMap<String , Object> error = new HashMap<>();
		error.put("msg", msg);
		error.put("state", "001");
		if(obj!=null && obj.length>0){
			error.put("data", obj[0]);
		}
		return error;
	}
	
	public Map<String, Object>  correct(String msg, Object... obj){
		HashMap<String , Object> correct = new HashMap<>();
		correct.put("msg", msg);
		correct.put("state", "000");
		if(obj!=null && obj.length>0){
			correct.put("data", obj[0]);
		}
		return correct;
	}

}
